#include "MessageQueue.h"
#include "SpdLog.h"

MessageQueue::MessageQueue()
{
	m_Queue.clear();
	m_AbortRequest = false;
}

MessageQueue::~MessageQueue()
{
	m_Queue.clear();
}

void MessageQueue::post(Message &msg)
{
	AutoLock lock(&m_Cond);
	auto start = m_Queue.begin();
    auto end = m_Queue.end();
    Message messag;
    /*删除队列中相同的事件*/
    while (start != end)
    {
		messag = *start;
		if(messag.what == msg.what) {
			m_Queue.erase(start);
		}
		++start;
    }
	m_Queue.push_back(msg);
	notify();
}

int MessageQueue::get(Message &msg)
{
	int ret = 0;
	while(true) {
		if (m_AbortRequest) {
	        ret = -1;
	        break;
	    }
		//wait until message is received
		if(isEmpty())
			wait();
		//read msg
		if(isEmpty())
			continue;
		
		AutoLock lock(&m_Cond);
		msg = m_Queue[0];
		if(!isEmpty())
			m_Queue.erase(m_Queue.begin());
		break;
	}
	return ret;
}
